<!-- 定义表单 表单中有表单项 表单需要绑定对象， 表单项需要绑定对象的成员变量 提交表单需要使用ajax方法提交json对象 -->
<!-- el-cascader 级联下拉选择框 需要通过options指定选项，这里绑定了options变量所以需要自己在data定义options 变量 绑定了change事件（当用户选择性的选项时候激活 handleChange，将多级选择的地址值组合 赋值给指定对象的属性）并且选中的值绑定给
selectedOptions
-->
<template>
    <div class="content">
      <el-dialog title="新增用戶" :visible.sync="addDialogIsShow" :before-close="handleClose" :close-on-click-modal="false">
        <el-form   label-width="100px"  ref="addCourseUploadForm" class="imgUploadForm" style="position: absolute;top: 300px;">
          <!-- 代码中的1表示第几个 和引入js的type变量对应 -->
          <!-- action 就是原来普通form action也就是提交地址 所以对应方法返回后端正确的action请求地址-->
          <el-form-item label="课程图片:"  style="margin-left: 0px;">
            <el-upload
              class="upload"
              :action="getUploadUrl"
              list-type="picture-card"
              :limit="limitNum"
              accept="image/*"
              :on-change="(file,fileList)=>{imgHandleChange(file,fileList,1,this,'addCourseUploadForm','course')}"
              :on-remove="(file,fileList)=>{imgHandleRemove(1,this,file)}"
              :on-before="(file,fileList)=>{imghandleBeforeUpload(file,1,this)}"
              :auto-upload="false"
              :file-list="fileList"
              ref="file1">
              <i class="el-icon-plus"></i>
            </el-upload>
            <!--<viewer-dialog ref="viewer" :images="imagesUp"></viewer-dialog>-->
          </el-form-item>
        </el-form>
      <el-form :model="course" :rules="addCourseRules" ref="addCourseForm">

        <el-form-item  label="课程号：" label-width="100px" prop="cno">
          <el-col :span="16">
           <el-input v-model="course.cno" placeholder="请填入课程号"/>
          </el-col>
        </el-form-item>

        <el-form-item  label="课程名称：" label-width="100px" prop="cname">
          <el-col :span="16">
           <el-input v-model="course.cname" placeholder="请填入课程名"/>
         </el-col>
        </el-form-item>


        <el-form-item  label="开设学期：" label-width="100px">
          <el-col :span="16">
            <el-input v-model="course.grade" placeholder="请填入学期"/>
          </el-col>
        </el-form-item>

       <div style="width:200px;height:200px;">

       </div>

        <el-form-item  label="课程简介：" label-width="100px" >
          <el-col :span="16">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="course.cdesc">
            </el-input>
          </el-col>
        </el-form-item>




        <el-row>
          <el-col :span="16">
            <span class="addSpan">&nbsp;</span>
          </el-col>
          <el-col :span="8">
        <el-button type="primary" @click="addCourse">添加课程</el-button>
            </el-col>
        </el-row>
      </el-form>
      </el-dialog>
    </div>
</template>

<script>
  import api from "../../../../axios/api.js"
  import utils from "../../../../static/js/utils/upload.js"
  import $ from 'jquery'
    export default {
        props:["addDialogIsShow"],
        name: "add",
        data(){
          return {
            course:{"imgs":""},//增加的时候需要说明要操作的成员变量避免出现undefined
            //校验
            addCourseRules: {
              cno: [
                {required: true, message: "学号不能为空", trigger: 'blur'},
                {validator: this.validateLength, trigger: 'blur'}
              ],
              cname: [{required: true, message: "姓名不能为空", trigger: 'blur'}]
            },
            //校验结束
            //上传使用
            fileList: [], //缓存区文件
            uploadFile:[], //  上传用文件
            formData:{files:[]},
            imagesUp:null,
            //上传使用结束
            test:true,
            limitNum:3
          }
        },
      methods:{
        addCourse:function () {
          this.$refs['addCourseForm'].validate(valid => {//此处refs对象和标签上的ref对应
            if (valid) {

              api.setDataFromAxios("/api/TestWeb/courseController/addCourse", this.course, "post", null).then(
                dto => {
                  this.$message.success("课程添加成功");
                  handleClose();
                }
              )
            } else {
              this.$message.warning("请正确格式填写后提交");
              return
            }
          })
        },
        //查询全部班级提供给下拉列表选择
        getAllClazzs:function(){
          api.setDataFromAxios("/api/TestWeb/clazzController/getClazzs",null,"get",null).then(
            dto=>{
              this.clazzes = dto.tList;
            }
          )
        },
        //行政区使用
        handleChange() {
          var loc = "";
          var regCode = "";
          for (let i = 0; i < this.selectedOptions.length; i++) {
            loc += CodeToText[this.selectedOptions[i]];
            regCode =this.selectedOptions[i]
          }
          console.log(loc);
          console.log(regCode);
          this.course.area = loc+","+regCode;
        },
        //行政区使用结束
         //提供给change事件刷新输入
        updateView(e) {
          this.$forceUpdate();
        },
        handleClose:function(){
          //给父组件传参
          this.$emit("closeAddDialog");
        },
        //多文件上传
        imghandleBeforeUpload(file,type,vm) {
          return utils.UPLOAD.Upload().handleBeforeUpload(file,type,vm);
        },
        imgHandleChange(file, fileList, type,vm,modelName,name) {
          // if(vm.fileList.length!=0){
          //   alert("请先删除再提交")
          //   return
          // }
          return utils.UPLOAD.Upload().handleChange(file, fileList, type,vm,modelName,name);
        },
        imgHandleRemove(type,vm,file) {

          let index =  utils.UPLOAD.Upload().handleRemove( type,vm,file);
          $(".el-upload--picture-card").css("display","inline-block");
          alert(index);
          console.log("----------777--------------");
          this.course.imgs = utils.UPLOAD.Upload().delStringByIndex(this.course.imgs,index);
          console.log(this.course.imgs);

          return index>0?true:false;
        },
        uploadImg:function(modelName,name,file){
          //  使用formdata格式
          let formData = new FormData();//准备一个空的表单对象
          formData.append("model",modelName);//图片上传子目录名放入表单对象
          if (this.formData.files[name]) {
            formData.append("file", this.formData.files[name]);//文件放入表单对象
          }
          //为什么要封装一下方法 1.每个vue组件有自己的一些参数处理，简化调用本来这个setDataFromAxios这个方法属于api 重新封装就属于当前页面
          api.setDataFromAxios("/api/TestWeb/uploadController/upload",formData,"post",{headers: { "Content-Type": "multipart/form-data" }})
            .then(dto=>{
              if(dto.code==200){
                this.$message.success (dto.msg);
                if (this.course.imgs==''){
                  this.course.imgs = dto.tList[0];//第一次增加特殊处理
                }else {
                  this.course.imgs = this.course.imgs + "," + dto.tList[0];
                }
                this.fileList.push(file);
                if (this.fileList.length==this.limitNum){
                    $(".el-upload--picture-card").css("display","none");
                }
                console.log("----------777--------------");
                console.log(this.course.imgs);
              }else{
                this.$message.error (dto.msg);
              }
            });//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
        },
        //多文件上传结束
      },
      created() {
      },
      computed:{
        getUploadUrl(){
          return      "/api/TestWeb/uploadController/upload";
        }
      },
    }
</script>

<style scoped lang="stylus">
   .content
     position relative
/deep/ .el-form-item__content
                  margin-left 0px;
</style>
